﻿using MS.Utility.Config;
using MS.Utility.EnumHelper;
using ServiceStack.Caching;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MS.Cache
{
    public class CacheAdapter
    {
        public static ICacheClient Cache = GetCache();
        private static ICacheClient GetCache()
        {
            //CacheType cacheType = CacheType.Memcache;
            var cacheType = EnumHelper.GetEnum(typeof(CacheType), CacheConfig.CacheType);
            ICacheClient cache = null;
            switch (int.Parse(cacheType.Key))
            {
                case (int)CacheType.MemoryCache:
                    cache = GetMemotyCache();
                    break;
             
                case (int)CacheType.Redis:
                    cache = GetRedis();
                    break;
             
                default:
                    cache = null;
                    break;
            }
            if (cache == null)
            {
                throw new Exception("配置文件未定义，或缓存配置错误");
            }
            return cache;
        }

        private static ICacheClient GetMemotyCache()
        {
            return new MemoryCacheClient();
        }
 

        private static ICacheClient GetRedis()
        {
            IRedisClientsManager iRedisClientsManager = new PooledRedisClientManager(string.Format("{0}:{1}", CacheConfig.CacheIP, int.Parse(CacheConfig.CachePort)));
            ICacheClient cache = (ICacheClient)iRedisClientsManager.GetCacheClient();
            return cache;
        }

   

        public enum CacheType
        {
            MemoryCache = 1,
            Redis = 2,
        }
    }
}
